/**
 * @name: user.controller
 * @data: 2024/4/2 17:09
 */
import {Body, Controller, Del, Get, Inject, Param, Post} from "@midwayjs/core";
import {UserService} from "../service/user.service";
import {Validate} from "@midwayjs/validate";
import Result from "../common/Result";
import ResultInterface from "../interface/Result";
import User from "../pojo/entity/user.entity";
import {UserInsertVO, UserLoginVo, UserUpdateVO,} from "../pojo/vo/user.vo";
import {HTTP_STATE_CODE} from "../common/const";
import {Context} from "@midwayjs/koa";

@Controller("/user")
export class UserController {

  @Inject()
  userService: UserService;
  @Inject()
  ctx: Context;

  /**
   * 新增用户
   * @param user 新增用户信息
   */
  @Post("/insert")
  // @ts-ignore
  @Validate(UserInsertVO)
  async insertUser(@Body() user: User): Promise<ResultInterface<User>> {
    try {
      //进行验证
      const userData = UserInsertVO.parse(user);
      //在新增前,确定username不存在
      const userList = await this.userService.selectUserByUsername(userData.username);
      if (userList.length > 0) {
        return Result<User>({
          code: HTTP_STATE_CODE.FORBIDDEN,
          msg: "添加失败,用户名已经存在",
        });
      } else {
        const result = await this.userService.insertUser(user);
        if (result) {
          return Result<User>({
            code: HTTP_STATE_CODE.SUCCESS,
            msg: "新增成功",
          });
        } else {
          return Result<User>({
            code: HTTP_STATE_CODE.ERROR,
            msg: "新增失败",
          });
        }
      }
    } catch (e) {
      return {
        code: HTTP_STATE_CODE.FORBIDDEN,
        msg: "缺少必填字段",
        data: null
      };
      // throw new HttpError(400,"缺少必填字段");
    }
  }

  @Post("/login")
  async login(@Body() user:User): Promise<ResultInterface<User>>{
    try {
      //进行验证
      const userData = UserLoginVo.parse(user);
      const userObject = await this.userService.login(userData.username,userData.password);
      if (userObject) {
        return Result<User>({
          code: HTTP_STATE_CODE.SUCCESS,
          msg: "登录成功",
          data:userObject
        });
      }else{
        return Result<User>({
          code: HTTP_STATE_CODE.ERROR,
          msg: "登录失败",
        });
      }
    }catch (e) {
      return {
        code: HTTP_STATE_CODE.FORBIDDEN,
        msg: "缺少必填字段",
        data: null
      };
    }
  }

  /**
   * 根据用户名查询用户
   * @param username
   */
  @Get(`/username/:username`)
  async selectUserByUsername(@Param("username") username: string): Promise<ResultInterface<User>> {
    const user = await this.userService.selectUserByUsername(username);
    if (user.length > 0) {
      return Result<User>({
        code: HTTP_STATE_CODE.SUCCESS,
        msg: "查询成功",
        data: user[0],
      });
    }
    return Result<User>({
      code: HTTP_STATE_CODE.FORBIDDEN,
      msg: "用户不存在",
    });
  }

  /**
   * 根据用户昵称查询用户列表
   * @param nickname
   */
  @Get("/nickname/:nickname")
  async selectUserByNickname(@Param("nickname") nickname: string): Promise<ResultInterface<User>> {
    const user = await this.userService.selectUserByNickname(nickname);
    if (user.length > 0) {
      return Result<User>({
        code: HTTP_STATE_CODE.SUCCESS,
        msg: "查询成功",
        data: user,
      });
    }
    return Result<User>({
      code: HTTP_STATE_CODE.FORBIDDEN,
      msg: "用户不存在",
    });
  }

  /**
   * 更新用户
   * @param user 更新后的用户信息
   */
  @Post("/update")
  async updateUser(@Body() user: User): Promise<ResultInterface<User>> {
    try {
      //注意,这里不可直接使用user,需要使用zod进行验证
      //进行验证
      const userData = UserUpdateVO.parse(user);
      const result: any = await this.userService.updateUser(userData as User);
      // console.log(97, result);
      if (result.changedRows > 0) {
        return Result<User>({
          code: HTTP_STATE_CODE.SUCCESS,
          msg: "修改成功",
        });
      } else {
        return Result<User>({
          code: HTTP_STATE_CODE.FORBIDDEN,
          msg: "修改失败",
        });
      }
    } catch (e) {
      return {
        code: HTTP_STATE_CODE.FORBIDDEN,
        msg: "缺少必填字段",
        data: null
      };
    }


  }

  /**
   * 删除用户
   * @param userId
   */
  @Del("/:userId")
  async deleteUserById(@Param("userId") userId: number): Promise<ResultInterface<User>> {
    const result = await this.userService.deleteUserById(userId);
    if (result.affected > 0) {
      return Result<User>({msg: "删除成功", code: HTTP_STATE_CODE.SUCCESS});
    } else {
      return Result<User>({msg: "删除失败", code: HTTP_STATE_CODE.FORBIDDEN});
    }
  }

  /**
   * 查询所有用户,无分页
   */
  @Get("/select")
  async selectUserByQuery() {
    try {
      const result = await this.userService.selectAllUser();
      if (result.length > 0) {
        return Result<User>({
          code: HTTP_STATE_CODE.SUCCESS,
          msg: "查询成功",
          data: result,
        });
      } else {
        return Result<User>({
          code: HTTP_STATE_CODE.NO_CONTENT,
          msg: "列表为空",
        });
      }
    } catch (e) {
      return Result<User>({
        code: HTTP_STATE_CODE.FORBIDDEN,
        msg: "缺少必填字段",
      });
    }

  }



}
